package com.welseyone.sc.service;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @Author: wesleyOne
 * @Email: wesleyone666@163.com
 * @Gitee: https://gitee.com/wesleyOne
 * @Date: 2020/8/29
 */
@Service
public class PaymentService {

    //========服务降级

    /**
     * 正常访问
     * @param id
     * @return
     */
    public String paymentInfo_OK(Integer id) {
        return "线程：" + Thread.currentThread().getName() + "OK_id:"+id;
    }

    /**
     * 超时
     * @param id
     * @return
     */
    @HystrixCommand(fallbackMethod = "paymentInfo_TimeoutHandler", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1500")
    })
    public String paymentInfo_Timeout(Integer id) {
        int timeout = 2000;
        try {
            TimeUnit.MILLISECONDS.sleep(timeout);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "线程：" + Thread.currentThread().getName() + "Timeout_id:"+id+",耗时"+timeout+"秒";
    }

    public String paymentInfo_TimeoutHandler(Integer id) {
        return "线程：" + Thread.currentThread().getName() + "Timeout_Handler_id:"+id+"，系统繁忙:8005！😭";
    }

    //========服务熔断

    @HystrixCommand(fallbackMethod = "paymentInfo_CircuitBreaker_fallback", commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),// 是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),// 请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"), // 时间窗口期
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60"),// 失败率达到多少后跳闸
    })
    public String paymentInfo_CircuitBreaker(Integer id) {
        if (id < 0) {
            throw new RuntimeException("****id不能为负数");
        }
        String simpleUUID = IdUtil.simpleUUID();
        return "线程：" + Thread.currentThread().getName() + "CircuitBreaker_id:"+id+",流水号："+simpleUUID;
    }

    public String paymentInfo_CircuitBreaker_fallback(Integer id) {
        return "线程：" + Thread.currentThread().getName() + "CircuitBreaker_Handler_id:"+id+"，系统繁忙:8005！😭";
    }
}
